/*
  Logging subroutine
*/

#include <msp430x16x.h>
#include <signal.h>

#include "../timing/timing.h"
#include "../adc/adc.h"
#include "../adcs/adcs.h"
#include "../sd/sd.h"

#define LOG_SIZE 30

/* Globally declared buffer */
unsigned char buffer[512];
int bufferPointer=0;

/* Converts hex to ascii */
void hex2ascii(int number, char *hex) {
  char digit, place;

  for (place=3;place>=0;place--) {
    digit=(char)(number & 0xF);
    if (digit<10) {
      hex[place]=48+digit;
    } else {
      hex[place]=55+digit;
    }
    number/=16;
  }
}

/* Write a log entry to the SD card */
int log_entry()
{
  int attitude[3], i, temperature;
  int j, current, time;
  unsigned char output[LOG_SIZE];
  char hex[4];
  unsigned long int address;

  //TODO: Get time index, increment, and add to output

  current=0;
  hex2ascii(time, hex); //convert time index to ascii
  for (j=0;j<4;j++) { //loop through 4 digits and store in output
    output[current++]=hex[j];
  }
  output[current++]=',';

  for(j=0;j<4;j++) output[current++]='0'; //No event occured
  output[current++]=',';
  for(j=0;j<4;j++) output[current++]='0'; //No event data
  output[current++]=',';

  //Hangs the MCU
  /*adcEnable(1);
  temperature=adcSample(10,1);
  ADCS(attitude);
  adcDisable();*/

  hex2ascii(temperature, hex);
  for (j=0;j<4;j++) { //loop through 4 digits and store in output
    output[current++]=hex[j];
  }
  output[current++]=',';

  for(i=0;i<3;i++) {
    hex2ascii(attitude[i], hex); //convert component of attitude data to hex
    for(j=0;j<4;j++) { //loop through 4 digits and store in output
      output[current++]=hex[j];
    }
    output[current++]=',';
  }

  output[current++]=';'; //terminate the line


  /* Writes ADCS and temp data 5 times for testing
  for(i=0; i<40; i++) {
    output[i]=(char)(attitude[0] & 0xff);
    output[i++]=(char)((attitude[0] & 0xff00)/256);
    output[i++]=(char)(attitude[1] & 0xff);
    output[i++]=(char)((attitude[1] & 0xff00)/256);
    output[i++]=(char)(attitude[2] & 0xff);
    output[i++]=(char)((attitude[2] & 0xff00)/256);
    output[i++]=(char)(temperature & 0xff);
    output[i++]=(char)((temperature & 0xff00)/256);
    }*/

  if (bufferPointer+LOG_SIZE>511) {
    address=0; //Temporary, for flight code must get address of SD card
    sd_write_block(address, buffer);
    bufferPointer=0;
    sdWait();
  }

  //Copies output block into buffer
  for (i=0;i<LOG_SIZE;i++)
    buffer[bufferPointer++]=output[i];

  return 16;
}

/* Writes a minilog entry to RAM for non-SD mode */
int minilog_entry(unsigned char *minilog) {
  int current=0;
  minilog[current++]='0'; //No event

  //TODO: Add minilog cautious data gathering

  return 8;
}
